package com.config.BasesSource;

import com.dao.dataSource.DataColumnMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.model.bo.ToSql;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author caiChaoqi
 * @Description 动态数据源通知
 * @Date 2018-06-23
 */
@Aspect
@Order(-1)//保证在@Transactional之前执行
@Component
public class DynamicDattaSourceAspect {

    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    DataColumnMapper dataColumnMapper;

    //改变数据源
    @Before("@annotation(com.model.pojo.annotation.TargetDataSource)")
    public void changeDataSource(JoinPoint joinPoint) {
        Object[] arr = joinPoint.getArgs();
        String joinStr = null;
        ToSql toSql = new ToSql();
//        System.out.println("数据源用户名"+baseName);

        try {
            joinStr = objectMapper.writeValueAsString(arr[1]);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        try {
            toSql = objectMapper.readValue(joinStr, ToSql.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        int baseId = toSql.getId();

        if (!DynamicDataSourceContextHolder.isContainsDataSource(String.valueOf(baseId))) {
            //joinPoint.getSignature() ：获取连接点的方法签名对象
            System.out.println("数据源 " + String.valueOf(baseId) + " 不存在使用默认的数据源 -> " + joinPoint.getSignature());
        } else {
            System.out.println("使用数据源：" +  String.valueOf(baseId));
            DynamicDataSourceContextHolder.setDataSourceType(String.valueOf(baseId));
        }
    }

    @After("@annotation(com.model.pojo.annotation.TargetDataSource)")
    public void clearDataSource(JoinPoint joinPoint) {
        System.out.println("清除数据源!");
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}
